package com.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blog.constants.SystemConstants;
import com.blog.domain.DTO.AddRoleDto;
import com.blog.domain.DTO.RoleListDto;
import com.blog.domain.DTO.StatusDto;
import com.blog.domain.ResponseResult;
import com.blog.domain.entity.Menu;
import com.blog.domain.entity.Role;
import com.blog.domain.entity.RoleMenu;
import com.blog.domain.vo.MenuTreeVo;
import com.blog.domain.vo.PageVo;
import com.blog.domain.vo.RoleEchoVo;
import com.blog.mapper.MenuMapper;
import com.blog.mapper.RoleMapper;
import com.blog.mapper.RoleMenuMapper;
import com.blog.service.MenuService;
import com.blog.service.RoleMenuService;
import com.blog.service.RoleService;
import com.blog.utils.BeanCopyUtils;
import com.blog.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色信息表(Role)表服务实现类
 *
 * @author makejava
 * @since 2024-09-11 14:24:02
 */
@Service("roleService")
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

	@Autowired
	private RoleMapper roleMapper;

	@Autowired
	private RoleMenuService roleMenuService;


	@Autowired
	private RoleMenuMapper roleMenuMapper;

	@Override
	public List<String> selectRoleKeyByUserId(Long userid) {

		//如果是管理员，返回集合中只需要有admin
		if (SecurityUtils.isAdmin()) {
			ArrayList<String> rolekeys = new ArrayList<>();
			rolekeys.add("admin");
			return rolekeys;
		}
		//若不是，查询用户所具有的角色信息
		return roleMapper.selectRoleKeyByUserId(userid);
	}

	/**角色分页查询
	 *
	 * @param pageNum
	 * @param pageSize
	 * @param roleListDto
	 * @return
	 */
	@Override
	public ResponseResult pageRoleselect(Integer pageNum, Integer pageSize,
	                                     RoleListDto roleListDto) {

		//分页条件
		Page<Role> page = new Page<>();
		page.setCurrent(pageNum);
		page.setSize(pageSize);
		//查询条件
		LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(StringUtils.hasText(roleListDto.getStatus()),
				Role::getStatus,roleListDto.getStatus());
		wrapper.like(StringUtils.hasText(roleListDto.getRoleName()),
				Role::getRoleName,roleListDto.getRoleName());

		wrapper.orderByAsc(Role::getRoleSort);
		//分页
		page(page,wrapper);

		//封装返回
		List<Role> records = page.getRecords();

		long total = page.getTotal();

		PageVo pageVo = new PageVo(records,total);

		return ResponseResult.okResult(pageVo);


	}

	/**更改角色状态
	 *
	 * @param statusDto
	 * @return
	 */
	@Override
	public ResponseResult updateRoleStatus(StatusDto statusDto) {
		Role role = getById(statusDto.getRoleId());
		role.setStatus(statusDto.getStatus());

		updateById(role);
		return ResponseResult.okResult();
	}

	/**新增角色
	 *
	 * @param addRoleDto
	 * @return
	 */
	@Override
	@Transactional
	public ResponseResult addRole(AddRoleDto addRoleDto) {

		//将用户信息保存到角色表
		Role role = BeanCopyUtils.copyBean(addRoleDto, Role.class);
		save(role);

		//将角色对应的菜单表保存到角色菜单表
		List<RoleMenu> roleMenuList = addRoleDto.getMenuIds().stream()
				.map(menuId -> new RoleMenu(role.getId(), menuId))
				.collect(Collectors.toList());

		roleMenuService.saveBatch(roleMenuList);


		return ResponseResult.okResult();

	}

	/**角色基础信息回显
	 *
	 * @param id
	 * @return
	 */
	@Override
	public ResponseResult getRoleDetailById(Long id) {
		Role role = getById(id);
		RoleEchoVo roleEchoVo = BeanCopyUtils.copyBean(role, RoleEchoVo.class);
		return ResponseResult.okResult(roleEchoVo);
	}

	/**根据角色id查询角色对应的菜单id
	 *
	 * @param id
	 * @return
	 */
	@Override
	public List<Long> getRoleAllMenuId(Long id) {
		//从role_Menu表中查询，根据roleid查询menuid集合
		List<Long> checkedKeys = roleMenuMapper.getRoleAllMenuId(id);
		return checkedKeys;
	}

	/**更新角色信息
	 *
	 * @param addRoleDto
	 * @return
	 */
	@Override
	@Transactional
	public ResponseResult updateRoleDetail(AddRoleDto addRoleDto) {
		//更新角色表中的信息
		updateById(BeanCopyUtils.copyBean(addRoleDto,Role.class));
		//更新角色菜单关联表中的数据
			//首先删除对应id的角色菜单数据
			LambdaQueryWrapper<RoleMenu> wrapper = new LambdaQueryWrapper<>();
			wrapper.eq(RoleMenu::getRoleId,addRoleDto.getId());
			roleMenuService.remove(wrapper);
			//再把新的角色菜单id批量插入
		List<Long> menuIds = addRoleDto.getMenuIds();
		List<RoleMenu> roleMenus = menuIds.stream()
				.map(menuId -> new RoleMenu(addRoleDto.getId(), menuId))
				.collect(Collectors.toList());
		roleMenuService.saveBatch(roleMenus);
		//返回
		return ResponseResult.okResult();
	}

	/**删除角色
	 *
	 * @param ids
	 * @return
	 */
	@Override
	public ResponseResult deleteRole(List<Long> ids) {
		removeByIds(ids);
		return ResponseResult.okResult();
	}

	/**查询角色列表
	 *
	 * @return
	 */

	@Override
	public ResponseResult getRoleList() {

		LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(Role::getStatus, SystemConstants.STATUS_NORMAL);
		List<Role> list = list(wrapper);
		return ResponseResult.okResult(list);

	}


}
